/**
 * Copyright &copy; 2012-2016 <a href="https://www.kaaction.com">KAA</a> All rights reserved All rights reserved.
 */
package com.kaaction.modules.ka.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.kaaction.common.config.Global;
import com.kaaction.common.persistence.Page;
import com.kaaction.common.web.BaseController;
import com.kaaction.common.utils.StringUtils;
import com.kaaction.modules.ka.entity.KaCanal;
import com.kaaction.modules.ka.service.KaCanalService;

/**
 * 渠道Controller
 * @author huanghaiming
 * @version 2017-06-14
 */
@Controller
@RequestMapping(value = "${adminPath}/ka/kaCanal")
public class KaCanalController extends BaseController {

	@Autowired
	private KaCanalService kaCanalService;
	
	@ModelAttribute
	public KaCanal get(@RequestParam(required=false) String id) {
		KaCanal entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = kaCanalService.get(id);
		}
		if (entity == null){
			entity = new KaCanal();
		}
		return entity;
	}
	
	@RequiresPermissions("ka:kaCanal:view")
	@RequestMapping(value = {"list", ""})
	public String list(KaCanal kaCanal, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<KaCanal> page = kaCanalService.findPage(new Page<KaCanal>(request, response), kaCanal); 
		model.addAttribute("page", page);
		return "modules/ka/kaCanalList";
	}

	@RequiresPermissions("ka:kaCanal:view")
	@RequestMapping(value = "form")
	public String form(KaCanal kaCanal, Model model) {
		model.addAttribute("kaCanal", kaCanal);
		return "modules/ka/kaCanalForm";
	}

	@RequiresPermissions("ka:kaCanal:edit")
	@RequestMapping(value = "save")
	public String save(KaCanal kaCanal, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, kaCanal)){
			return form(kaCanal, model);
		}
		int cnt = kaCanalService.getEqual(kaCanal);
		if(cnt>0){
			model.addAttribute("message", "该渠道已存在");
			return form(kaCanal, model);
		}
		kaCanalService.save(kaCanal);
		addMessage(redirectAttributes, "保存渠道成功");
		return "redirect:"+Global.getAdminPath()+"/ka/kaCanal/?repage";
	}
	
	@RequiresPermissions("ka:kaCanal:delete")
	@RequestMapping(value = "delete")
	public String delete(KaCanal kaCanal, RedirectAttributes redirectAttributes) {
		kaCanalService.delete(kaCanal);
		addMessage(redirectAttributes, "删除渠道成功");
		return "redirect:"+Global.getAdminPath()+"/ka/kaCanal/?repage";
	}

}